package com.identify.controller;

import com.identify.context.BaseContext;
import com.identify.mapper.FileDetailMapper;
import com.identify.pojos.entity.FileDetail;
import com.identify.pojos.entity.Result;
import com.identify.pojos.vos.IdentificationResultVo;
import com.identify.service.InferenceService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.codec.digest.DigestUtils;


import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileDetailController {

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @Autowired
    private FileDetailMapper fileDetailMapper;

    @Autowired
    private InferenceService inferenceService;

    /**
     * 上传文件，并记录到数据库,并进行识别
     */
    @PostMapping("/upload")
    public Result<IdentificationResultVo> upload(MultipartFile file) {
        log.info("文件上传:{}", file.getOriginalFilename());

        try (InputStream inputStream = file.getInputStream()) {
            // 1. 计算文件hash
            String fileHash = DigestUtils.md5Hex(inputStream);

            // 2. 检查文件是否已存在
            QueryWrapper<FileDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("file_hash", fileHash);
            FileDetail existingFile = fileDetailMapper.selectOne(queryWrapper);

            String fileUrl;
            if (existingFile != null) {
                // 文件已存在，直接使用现有URL
                log.info("检测到重复文件，文件名: {}, Hash: {}", file.getOriginalFilename(), fileHash);
                fileUrl = existingFile.getFileUrl();
            } else {
                // 文件不存在，上传新文件
                log.info("新文件上传，文件名: {}", file.getOriginalFilename());
                FileInfo fileInfo = fileStorageService.of(file)
                        .upload();
                if (fileInfo == null) {
                    return Result.error("文件上传失败");
                }
                fileUrl = fileInfo.getUrl();

                // 将新文件信息存入数据库
                FileDetail fileDetail = FileDetail.builder()
                        .userId(BaseContext.getCurrentId())
                        .fileUrl(fileUrl)
                        .fileName(file.getOriginalFilename())
                        .fileHash(fileHash) // 存储hash
                        .createTime(LocalDateTime.now())
                        .build();
                fileDetailMapper.insert(fileDetail);
            }

            // 3. 对图片进行识别
            List<com.identify.pojos.entity.Detection> detections = inferenceService.identify(fileUrl);

            // 4. 封装返回结果
            IdentificationResultVo resultVo = IdentificationResultVo.builder()
                    .fileUrl(fileUrl)
                    .detections(detections)
                    .build();

            return Result.success(resultVo);

        } catch (Exception e) {
            log.error("文件上传或识别过程中发生错误", e);
            return Result.error("文件处理失败: " + e.getMessage());
        }
    }

}
